package com.lcj.interceptor;

import com.lcj.entity.Users;
import com.lcj.exception.AuthFailException;
import com.lcj.mapper.UserMapper;
import com.lcj.utils.JwtService;
import com.lcj.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthIntercepter implements HandlerInterceptor {
    @Autowired
    private JwtService jwtService;
    @Autowired
    private UserMapper userMapper;

    private void throwAuthFailException() throws AuthFailException {
        throw new AuthFailException(401, "认证失败");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        String token = request.getHeader("Authorization");
        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        try{if (token != null) {
            String userId = null;
            if (jwtService.validateToken(token)) {
                userId = jwtService.getSub(token);
                Users users = userMapper.selectById(userId);
                UserUtils.setLoginUser(users);
                System.out.println("users"+users);
                return true;

            } else {
                throwAuthFailException();
                return false;
            }

        } else {
            if ((requestURI.matches("/api/articles.*?"))
                    && method.toLowerCase().equals("get")) {
                return true;
            } else {

                throwAuthFailException();
                return false;
            }


        }}catch (Exception e){
            throwAuthFailException();
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
